package com.atg.atgchat.init.user.service.imp;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.atg.atgchat.init.common.utils.JsonUtils;
import com.atg.atgchat.init.common.vo.response.ApiResult;
import com.atg.atgchat.init.user.dao.UserDao;
import com.atg.atgchat.init.user.mapper.ItemConfigMapper;
import com.atg.atgchat.init.user.model.dto.IpResult;
import com.atg.atgchat.init.user.model.entity.IpDetail;
import com.atg.atgchat.init.user.model.entity.IpInfo;
import com.atg.atgchat.init.user.model.entity.ItemConfig;
import com.atg.atgchat.init.user.model.entity.User;
import com.atg.atgchat.init.user.service.IpService;
import com.atg.atgchat.init.user.service.ItemConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/*
author: atg
time: 2025/1/16 15:43
*/

@Slf4j
@Service
public class IpServiceImpl implements IpService, DisposableBean {
    @Resource
    private UserDao userDao;
    // 创建一个线程
    private static final ExecutorService executor = new ThreadPoolExecutor(
            1,
            1,
            0L,
            java.util.concurrent.TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(500),
            new NamedThreadFactory("refresh-ipDetail", false)
    );

    @Override
    public void refreshIpDetail(Long uid) {
        executor.execute(() -> {
            // 获取用户ip
            User user = userDao.getById(uid);
            IpInfo ipInfo = user.getIpInfo();
            if (ipInfo == null) {
                log.error("IpInfo is null for user with id: {}", uid);
                // 初始化IpInfo并保存到数据库
                return;
            }
            if (Objects.isNull(ipInfo)) {
                return;
            }
            String ip = ipInfo.needRefreshIp();
            if (StringUtils.isBlank(ip)) {
                return;
            }
            tryGetIpDetail(ip);

        });

    }

    private static IpDetail tryGetIpDetail(String ip) {
        for (int i = 0; i < 3; i++) {
            IpDetail ipDetail = getIpDetail(ip);
            if (Objects.nonNull(ipDetail)) {
                return ipDetail;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static IpDetail getIpDetail(String ip) {
        String url = "https://ip.taobao.com/outGetIpInfo?ip=" + ip + "&accessKey=alibaba-inc";
        try {
            String data = HttpUtil.get(url);
//            ApiResult<IpDetail> apiResult = new ApiResult<>();

            IpResult<IpDetail> result = JSONUtil.toBean(data, new TypeReference<IpResult<IpDetail>>() {
            }, false);
            IpDetail data1 = result.getData();
            if (result.isSuccess() && Objects.nonNull(data1)) {
                return data1;
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    public static void main(String[] args) {
        Date begin = new Date();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            executor.execute(() -> {
                IpDetail ipDetail = tryGetIpDetail("43.139.78.42");
                if (Objects.nonNull(ipDetail)) {
                    Date date = new Date();
                    System.out.println(String.format("第%d次成功，目前耗时%dms", finalI, (date.getTime() - begin.getTime())));
                }
            });
//        String encoding = System.getProperty("file.encoding");
//        System.out.println("Current file encoding: " + encoding);
//        System.out.println("Current default charset: " + Charset.defaultCharset());
//        System.out.println("第%d次成功");

        }
    }
    @Override
    public void destroy() throws InterruptedException {
        executor.shutdown();
        if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {//最多等30秒，处理不完就拉倒
            if (log.isErrorEnabled()) {
                log.error("Timed out while waiting for executor [{}] to terminate", executor);
            }
        }
    }


}
